package com.program.facesigninsystem.controller;

import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.program.facesigninsystem.entity.*;
import com.program.facesigninsystem.iteration.entity.SigninclassEntity;
import com.program.facesigninsystem.service.*;
import com.program.facesigninsystem.util.GetInfoUtil;
import com.program.facesigninsystem.util.PageUtil;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import net.sf.json.JSONObject;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.logging.Level;
import java.util.logging.Logger;

@CrossOrigin
@RestController
@RequestMapping(value = "/org")
public class OrganizationController {
    private static Logger log = Logger.getLogger(SignInActivityController.class.toString());
    private static final int LOCATION = 522;
    private static final int CODE = 829;
    @Resource
    IOrganizationService iOrganizationService;
    @Resource
    IUserInfoService iUserInfoService;
    @Resource
    ISignInCourseService iSignInCourseService;
    @Resource
    ISignInRecordService iSignInRecordService;
    @Resource
    SignInClassService signInClassService;

    @ApiOperation("创建组织")
    @RequestMapping(value = "/createneworg", method = RequestMethod.POST)
    public ResponseModel createnewOrganization(@RequestParam String uid, @RequestParam String oname, @RequestParam String email, @RequestParam String phone) {
        String oId = GetInfoUtil.getId();
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String currentTime = dateFormat.format(System.currentTimeMillis());
        UUID uuid = UUID.randomUUID();
        String ocode = uuid.toString().substring(0, 8);//自动生成一个组织码
        if (iOrganizationService.addNewOrganization(oId, oname, email, currentTime, ocode, phone, uid))
            return new ResponseModel(200, "创建成功", ocode);
        else
            return new ResponseModel(500, "创建失败");
    }

    @ApiOperation("根据组织码搜索组织")
    @GetMapping("/selectbyocode")
    public ResponseModel selectbyocode(@RequestParam String ocode) {
        Organization organization = iOrganizationService.selectbyocode(ocode);
        JSONObject data = new JSONObject();
        data.put("oid", organization.getOid());
        data.put("oname", organization.getOname());
        data.put("email", organization.getEmail());
        data.put("createtime", organization.getCreatetime());
        data.put("ocode", organization.getOcode());
        data.put("phone", organization.getPhone());
        Map<String, Object> user = iUserInfoService.selectUser(organization.getUid());
        data.put("name", user.get("name"));
        if (organization != null)
            return new ResponseModel(200, "搜索成功", data);
        else
            return new ResponseModel(500, "组织码不正确");
    }

    @ApiOperation("根据用户id搜索组织")
    @GetMapping("/selectbyuid")
    public void selectbyuid(
            HttpServletResponse resp,
            @RequestParam String uid,
            @RequestParam(value = "pageNum", required = false, defaultValue = "1") int pageNum,
            @RequestParam(value = "pageSize", required = false, defaultValue = "10") int pageSize
    ) {
        List<Organization> organizationList = iOrganizationService.selectorgbyuid(uid, pageSize, pageNum);
        List<JSONObject> data = new ArrayList<>();
        try {
            for (Organization organization : organizationList) {
                JSONObject activityObject = new JSONObject();
                activityObject.put("oid", organization.getOid());
                activityObject.put("oname", organization.getOname());
                activityObject.put("email", organization.getEmail());
                activityObject.put("createtime", organization.getCreatetime());
                activityObject.put("ocode", organization.getOcode());
                activityObject.put("phone", organization.getPhone());
                data.add(activityObject);
            }
            JSONObject data1 = PageUtil.wrap(data, "data", pageSize, pageNum);
            resp.setCharacterEncoding("utf-8");
            /*得到输出流*/
            PrintWriter respWriter = resp.getWriter();
            /*将JSON格式的对象toString()后发送*/
            respWriter.append(data1.toString());
        } catch (Exception e) {
            log.log(Level.SEVERE, "Error parsing date", e);
        }
    }

    @ApiOperation("删除组织")
    @RequestMapping(value = "/deleorg", method = RequestMethod.GET)
    public ResponseModel deleteOrgbyoid(@RequestParam("oid") String oid) {
        try {
            iOrganizationService.deletebyoid(oid);
            return new ResponseModel(200, "删除成功");
        } catch (Exception e) {
            log.log(Level.SEVERE, "Error parsing date", e);
            return new ResponseModel(113, "删除失败");
        }
    }

    @ApiOperation("申请加入组织")
    @RequestMapping(value = "/applygroup", method = RequestMethod.POST)
    public ResponseModel applygroup(@RequestParam String oid, @RequestParam String sid) {
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String currentTime = dateFormat.format(System.currentTimeMillis());
        if (iOrganizationService.applygroup(oid, sid, currentTime))
            return new ResponseModel(200, "申请成功");
        else
            return new ResponseModel(500, "申请失败,在申请中或者已经加入该组织");
    }

    @ApiOperation("驳回申请")
    @RequestMapping(value = "/rejectapply", method = RequestMethod.POST)
    public ResponseModel rejectapply(@RequestParam String soid) {
        if (iOrganizationService.rejectapply(soid))
            return new ResponseModel(200, "拒绝加入成功");
        else
            return new ResponseModel(500, "拒绝失败");
    }

    @ApiOperation("通过申请")
    @RequestMapping(value = "/passapply", method = RequestMethod.POST)
    public ResponseModel passapply(@RequestParam String soid) {
        if (iOrganizationService.passapply(soid))
            return new ResponseModel(200, "批准申请成功");
        else
            return new ResponseModel(500, "批准申请失败");
    }

    @ApiOperation("解除绑定")
    @RequestMapping(value = "/untiebind", method = RequestMethod.POST)
    public ResponseModel untiebind(@RequestParam String soid) {
        if (iOrganizationService.untiebind(soid))
            return new ResponseModel(200, "解除绑定成功");
        else
            return new ResponseModel(500, "解除绑定失败");
    }

    @ApiOperation("查看申请记录")
    @RequestMapping(value = "/applyhistory", method = RequestMethod.GET)
    public void selectapplyhistory(
            HttpServletResponse resp,
            @RequestParam String oid,
            @RequestParam(value = "pageNum", required = false, defaultValue = "1") int pageNum,
            @RequestParam(value = "pageSize", required = false, defaultValue = "10") int pageSize
    ) {
        List<JSONObject> data = iOrganizationService.selectapplyhistory(oid, pageSize, pageNum);
        try {
            JSONObject data1 = PageUtil.wrap(data, "data", pageSize, pageNum);
            resp.setCharacterEncoding("utf-8");
            /*得到输出流*/
            PrintWriter respWriter = resp.getWriter();
            /*将JSON格式的对象toString()后发送*/
            respWriter.append(data1.toString());
        } catch (Exception e) {
            log.log(Level.SEVERE, "Error parsing date", e);
        }
    }

    @ApiOperation("查看绑定的下级组织")
    @RequestMapping(value = "/applybind", method = RequestMethod.GET)
    public void selectbind(
            HttpServletResponse resp,
            @RequestParam String oid,
            @RequestParam(value = "pageNum", required = false, defaultValue = "1") int pageNum,
            @RequestParam(value = "pageSize", required = false, defaultValue = "10") int pageSize
    ) {
        List<JSONObject> data = iOrganizationService.selectbind(oid, pageSize, pageNum);
        try {
            JSONObject data1 = PageUtil.wrap(data, "data", pageSize, pageNum);
            resp.setCharacterEncoding("utf-8");
            /*得到输出流*/
            PrintWriter respWriter = resp.getWriter();
            /*将JSON格式的对象toString()后发送*/
            respWriter.append(data1.toString());
        } catch (Exception e) {
            log.log(Level.SEVERE, "Error parsing date", e);
        }
    }

    @ApiOperation("获取完整组织树（所有下级）")
    @RequestMapping(value = "/fullorgtree", method = RequestMethod.GET)
    public void fullOrgTree(
            HttpServletResponse resp,
            @RequestParam String oid
    ) {
        resp.setCharacterEncoding("utf-8");
        try {
            if (StringUtils.isBlank(oid)) {
                resp.sendError(HttpServletResponse.SC_BAD_REQUEST, "组织ID不能为空");
                return;
            }

            JSONObject data = iOrganizationService.buildFullOrgTree(oid);
            if (data == null) {
                resp.sendError(HttpServletResponse.SC_NOT_FOUND, "未找到对应组织信息");
                return;
            }

            PrintWriter respWriter = resp.getWriter();
            respWriter.append(data.toString());
        } catch (Exception e) {
            log.log(Level.SEVERE, "Error generating org tree", e);
            try {
                resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "服务器异常");
            } catch (IOException ioException) {
                log.log(Level.SEVERE, "Error writing error response", ioException);
            }
        }
    }


    @ApiOperation("查看绑定的上级组织")
    @RequestMapping(value = "/applybindsup", method = RequestMethod.GET)
    public void selectbindsup(
            HttpServletResponse resp,
            @RequestParam String oid,
            @RequestParam(value = "pageNum", required = false, defaultValue = "1") int pageNum,
            @RequestParam(value = "pageSize", required = false, defaultValue = "10") int pageSize
    ) {
        List<JSONObject> data = iOrganizationService.selectsup(oid, pageSize, pageNum);
        try {
            JSONObject data1 = PageUtil.wrap(data, "data", pageSize, pageNum);
            resp.setCharacterEncoding("utf-8");
            /*得到输出流*/
            PrintWriter respWriter = resp.getWriter();
            /*将JSON格式的对象toString()后发送*/
            respWriter.append(data1.toString());
        } catch (Exception e) {
            log.log(Level.SEVERE, "Error parsing date", e);
        }
    }
    @ApiOperation("查看绑定的上级组织绑定历史记录")
    @RequestMapping(value = "/applybindhistory", method = RequestMethod.GET)
    public void selectbindhistory(
            HttpServletResponse resp,
            @RequestParam String oid,
            @RequestParam(value = "pageNum", required = false, defaultValue = "1") int pageNum,
            @RequestParam(value = "pageSize", required = false, defaultValue = "10") int pageSize
    ) {
        List<JSONObject> data = iOrganizationService.selectbdhistory(oid, pageSize, pageNum);
        try {
            JSONObject data1 = PageUtil.wrap(data, "data", pageSize, pageNum);
            resp.setCharacterEncoding("utf-8");
            /*得到输出流*/
            PrintWriter respWriter = resp.getWriter();
            /*将JSON格式的对象toString()后发送*/
            respWriter.append(data1.toString());
        } catch (Exception e) {
            log.log(Level.SEVERE, "Error parsing date", e);
        }
    }
    @ApiOperation("修改组织信息")
    @RequestMapping(value = "/updateorg", method = RequestMethod.POST)
    public ResponseModel updateorg(@RequestParam String oid, @RequestParam String oname, @RequestParam String email,  @RequestParam String phone) {
        if (iOrganizationService.updatebyoid(oid, oname, email, phone))
            return new ResponseModel(200, "修改成功");
        else
            return new ResponseModel(500, "修改失败");
    }

    @ApiOperation("根据组织名搜索组织")
    @GetMapping("/selectbyoname")
    public void selectbyoname(HttpServletResponse resp,
                              @RequestParam String oname,
                              @RequestParam String uid,
                              @RequestParam(value = "pageNum", required = false, defaultValue = "1") int pageNum,
                              @RequestParam(value = "pageSize", required = false, defaultValue = "10") int pageSize) {
        List<Organization> organizationList = iOrganizationService.selectorgbyoname(oname, uid,pageSize, pageNum);
        List<JSONObject> data = new ArrayList<>();
        try {
            for (Organization organization : organizationList) {
                JSONObject activityObject = new JSONObject();
                activityObject.put("oid", organization.getOid());
                activityObject.put("oname", organization.getOname());
                activityObject.put("email", organization.getEmail());
                activityObject.put("createtime", organization.getCreatetime());
                activityObject.put("ocode", organization.getOcode());
                activityObject.put("phone", organization.getPhone());
                data.add(activityObject);
            }
            JSONObject data1 = PageUtil.wrap(data, "data", pageSize, pageNum);
            resp.setCharacterEncoding("utf-8");
            /*得到输出流*/
            PrintWriter respWriter = resp.getWriter();
            /*将JSON格式的对象toString()后发送*/
            respWriter.append(data1.toString());
        } catch (Exception e) {
            log.log(Level.SEVERE, "Error parsing date", e);
        }
    }

    @ApiOperation("查看绑定的下级组织根据组织名")
    @RequestMapping(value = "/applybindbyoname", method = RequestMethod.GET)
    public void selectbindbyoname(
            HttpServletResponse resp,
            @RequestParam String oid,
            @RequestParam String oname,
            @RequestParam(value = "pageNum", required = false, defaultValue = "1") int pageNum,
            @RequestParam(value = "pageSize", required = false, defaultValue = "10") int pageSize
    ) {
        List<JSONObject> data = iOrganizationService.selectbindbyoname(oid, oname, pageSize, pageNum);
        try {
            JSONObject data1 = PageUtil.wrap(data, "data", pageSize, pageNum);
            resp.setCharacterEncoding("utf-8");
            /*得到输出流*/
            PrintWriter respWriter = resp.getWriter();
            /*将JSON格式的对象toString()后发送*/
            respWriter.append(data1.toString());
        } catch (Exception e) {
            log.log(Level.SEVERE, "Error parsing date", e);
        }
    }

    @ApiOperation("是否允许查看下级组织")
    @RequestMapping(value = "/whethersee", method = RequestMethod.GET)
    public ResponseModel whethersee(@RequestParam("oid") String oid, @RequestParam("sid") String sid) {
        try {
            if (iOrganizationService.selectwethersee(oid, sid)) {
                return new ResponseModel(200, "查询成功");
            }
            return new ResponseModel(113, "下级关闭查看考勤情况");
        } catch (Exception e) {
            log.log(Level.SEVERE, "Error parsing date", e);
            return new ResponseModel(113, "查询失败");
        }
    }

    @ApiOperation("更改开启或关闭考勤")
    @RequestMapping(value = "/updatewhethersee", method = RequestMethod.POST)
    public ResponseModel updatewhethersee(@RequestParam("oid") String oid, @RequestParam("sid") String sid, @RequestParam("whethersee") String whethersee) {
        if (iOrganizationService.updatewhethersee(oid, sid, whethersee)) {
            return new ResponseModel(200, "更改成功");
        }else{
                return new ResponseModel(113, "更新失败");
        }

    }
    @ApiOperation("查找所有下级组织")
    @RequestMapping(value = "/selectjunior", method = RequestMethod.GET)
    public ResponseModel selectjunior(@RequestParam("oid") String oid) {
        if (iOrganizationService.selectjunior(oid)!=null) {
            return new ResponseModel(200, "更改成功",iOrganizationService.selectjunior(oid));
        }else{
            return new ResponseModel(113, "更新失败");
        }
    }
    @ApiOperation("统计组织")
    @RequestMapping(value = "/statisticorganization", method = RequestMethod.GET)
    public ResponseModel statisticorganization(@RequestParam("oid") String oid,@RequestParam("year") String year,@RequestParam("semester") String semester,@RequestParam("startweek") String startweek,@RequestParam("endweek") String endweek, @RequestParam("section") String section) {
        ResponseModel responseModel;
        try {
            int sum=0;
            int count = 0;
            int qiandao=0;
            int qingjia=0;
            int chidao=0;
            int qita=0;
            int weirenzheng=0;
            int kuangke=0;
            List<String> ccidlist=iOrganizationService.selectccidfortj(oid, year, semester, startweek, endweek, section);
            for(String ccid:ccidlist){
                List<String> lidlist=iSignInCourseService.selectlidbyccid(ccid);
                for(String lid:lidlist){
                    SigninclassEntity signinclassEntity = signInClassService.selectClassbylid(lid);

                    count += iSignInRecordService.selectRecCount(lid);
                    qiandao +=iSignInRecordService.selectRecCount1(lid,1);
                    qingjia +=iSignInRecordService.selectRecCount1(lid,2);
                    chidao +=iSignInRecordService.selectRecCount1(lid,3);
                    qita +=iSignInRecordService.selectRecCount1(lid,4);
                    weirenzheng +=iSignInRecordService.selectRecCount1(lid,5);
                    kuangke +=iSignInRecordService.selectRecCount1(lid,6);
                    if (signinclassEntity != null) {
                        sum+=signinclassEntity.getNumber();
                    }else{
                        sum+=count;
                    }
                }
            }
            ArrayList<Object> data = new ArrayList<>();
            Map<String, Object> map = new HashMap<>(1);
            map.put("总人数", sum);
            map.put("已签到", count);
            map.put("签到", qiandao);
            map.put("请假", qingjia);
            map.put("迟到", chidao);
            map.put("其他", qita);
            map.put("未认证", weirenzheng);
            map.put("旷课", kuangke);
            data.add(0, map);
            responseModel = new ResponseModel(200, "获取成功", data);
        } catch (Exception e) {
            responseModel = new ResponseModel(199, "无正在进行的考勤");
        }
        return responseModel;
    }
}
